package zwxsrv

import (
	"crypto/sha1"
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"sort"
	"strings"
)

func makeSignature(atoken, timestamp, nonce string) string {
	sl := []string{atoken, timestamp, nonce}
	sort.Strings(sl)
	s := sha1.New()
	io.WriteString(s, strings.Join(sl, ""))
	return fmt.Sprintf("%x", s.Sum(nil))
}

func parseRequestBody(r *http.Request) (*RequestBody, error) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}

	requestBody := &RequestBody{}
	if err := xml.Unmarshal(body, requestBody); err != nil {
		log.Println("Unmarshal xml error:", err)
		log.Println("body:", string(body))
		return nil, err
	}
	return requestBody, nil
}

func validateUrl(w http.ResponseWriter, r *http.Request) bool {
	timestamp := strings.Join(r.Form["timestamp"], "")
	nonce := strings.Join(r.Form["nonce"], "")
	signatureIn := strings.Join(r.Form["signature"], "")

	signatureGen := makeSignature(gCfg.WxToken, timestamp, nonce)
	if signatureGen != signatureIn {
		return false
	}

	// 回复echostr
	echostr := strings.Join(r.Form["echostr"], "")
	if len(echostr) > 10 {
		fmt.Fprintf(w, echostr)
		log.Println("return echostr:", echostr)
	}

	return true
}
